package com.myproject.zhujiemian;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import com.itheima.tencentqq52.R;
import com.myproject.biji.bijiMainActivity;
import com.myproject.clander.CalendarAdapter;
import com.myproject.database.EveryDayTask;
import com.myproject.database.MYdatabase;
import com.myproject.database.MyAdapter;
import com.myproject.zidingyikongjian.DragLayout;
import com.myproject.zidingyikongjian.LLinearLayout;
import com.myproject.zidingyikongjian.MyLinearLayout;
import com.myproject.zidingyikongjian.DragLayout.OnDragStatusChangeListener;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.CycleInterpolator;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class JianchiPage extends Activity implements OnGestureListener {

	private DragLayout jianchi_zuobuju;
	private LLinearLayout jianchi_zhubuju;
	private ListView everydaytasklist;

	private Cursor cursor;
	private SQLiteDatabase EveryDaytaskReader;
	private EveryDayTask taskDB;
	private EveryDayTaskAdapter adapter;

	int gvFlag = 0; // 每次添加gridview到viewflipper中时给的标记
	private String val;
	private GestureDetector gestureDetector = null;
	private CalendarAdapter calV = null;
	private GridView gridView = null;
	private TextView topText = null;
	private static int jumpMonth = 0; // 每次滑动，增加或减去一个月,默认为0（即显示当前月）
	private static int jumpYear = 0; // 滑动跨越一年，则增加或者减去一年,默认为0(即当前年)
	private int year_c = 0;
	private int month_c = 0;
	private int day_c = 0;
	private String currentDate = "";
	private Bundle bd = null;// 发送参数
	private Bundle bun = null;// 接收参数
	private String ruzhuTime;
	private String lidianTime;
	private String state = "";

	public JianchiPage() {

		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
		currentDate = sdf.format(date); // 当期日期
		year_c = Integer.parseInt(currentDate.split("-")[0]);
		month_c = Integer.parseInt(currentDate.split("-")[1]);
		day_c = Integer.parseInt(currentDate.split("-")[2]);

	}

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.calendar);
		val = getIntent().getStringExtra("flag");
		
		taskDB = new EveryDayTask(this);
		EveryDaytaskReader = taskDB.getReadableDatabase();

		jianchi_zuobuju = (DragLayout) findViewById(R.id.jianchi_zuobuju);

		jianchi_zhubuju = (LLinearLayout) findViewById(R.id.jianchi_zhubuju);
		// 查找Draglayout, 设置监听
		DragLayout mDragLayout = (DragLayout) findViewById(R.id.jianchi_zuobuju);

		// 设置引用
		jianchi_zhubuju.setDraglayout(mDragLayout);

		mDragLayout.setDragStatusListener(new OnDragStatusChangeListener() {

			@Override
			public void onOpen() {
			}

			@Override
			public void onDraging(float percent) {
			}

			@Override
			public void onClose() {

			}
		});

		
		everydaytasklist = (ListView) findViewById(R.id.jianchi_left);
		
				
//				@Override
//	            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,  
//	                    int arg2, long arg3) {  
//	                // TODO Auto-generated method stub  
//	                index = arg2;  
//	                return false;  
//	            }  
//	        });  
		
			
		bd = new Bundle();// out
		bun = getIntent().getExtras();// in

		if (bun != null && bun.getString("state").equals("ruzhu")) {
			state = bun.getString("state");
			System.out.println("%%%%%%" + state);
		} else if (bun != null && bun.getString("state").equals("lidian")) {

			state = bun.getString("state");
			System.out.println("|||||||||||" + state);
		}

		gestureDetector = new GestureDetector(this);
		// bd=new Bundle();
		calV = new CalendarAdapter(this, getResources(), jumpMonth, jumpYear,
				year_c, month_c, day_c);
		addGridView();
		gridView.setAdapter(calV);

		topText = (TextView) findViewById(R.id.tv_month);
		addTextToTopTextView(topText);

	}

	// ToCalenderright

	// 日历翻转
	public void ToCalenderright(View view) {
		// 像左滑动
		addGridView(); // 添加一个gridView
		jumpMonth++; // 下一个月

		calV = new CalendarAdapter(this, getResources(), jumpMonth, jumpYear,
				year_c, month_c, day_c);
		gridView.setAdapter(calV);
		addTextToTopTextView(topText);
		gvFlag++;
	}

	public void ToCalenderleft(View view) {

		// 向右滑动
		addGridView(); // 添加一个gridView
		jumpMonth--; // 上一个月

		calV = new CalendarAdapter(this, getResources(), jumpMonth, jumpYear,
				year_c, month_c, day_c);
		gridView.setAdapter(calV);
		gvFlag++;
		addTextToTopTextView(topText);
	}

	// 跳转到统计页面
	public void ToTongjiPage(View view) {
		Intent intent = new Intent(this, TongjiPage.class);
		intent.setAction("com.myproject.TongjiPage");
		startActivity(intent);
	}

	// 跳转到任务页面
	public void ToRenwuPage(View view) {
		Intent intent = new Intent(this, MainActivity.class);
		intent.setAction("android.intent.action.MAIN");
		startActivity(intent);
	}

	// 跳转到添加每日任务页面

	public void ToAddEveryDayTask(View view) {
		Intent intent = new Intent(this, AddEveryDayTask.class);
		intent.setAction("com.myproject.AddEveryDayTask");
		startActivity(intent);
	}

	// 显示左布局
	public void ToJianchiZuobuju(View view) {
		jianchi_zuobuju.open(true);
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {

		if (e1.getX() - e2.getX() > 120) {
			// 像左滑动
			addGridView(); // 添加一个gridView
			jumpMonth++; // 下一个月

			calV = new CalendarAdapter(this, getResources(), jumpMonth,
					jumpYear, year_c, month_c, day_c);
			gridView.setAdapter(calV);
			addTextToTopTextView(topText);
			gvFlag++;

			return true;
		} else if (e1.getX() - e2.getX() < -120) {
			// 向右滑动
			addGridView(); // 添加一个gridView
			jumpMonth--; // 上一个月

			calV = new CalendarAdapter(this, getResources(), jumpMonth,
					jumpYear, year_c, month_c, day_c);
			gridView.setAdapter(calV);
			gvFlag++;
			addTextToTopTextView(topText);

			return true;
		}
		return false;
	}

	/**
	 * 创建菜单
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, menu.FIRST, menu.FIRST, "今天");
		return super.onCreateOptionsMenu(menu);
	}

	/**
	 * 选择菜单
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case Menu.FIRST:
			// 跳转到今天
			int xMonth = jumpMonth;
			int xYear = jumpYear;
			int gvFlag = 0;
			jumpMonth = 0;
			jumpYear = 0;
			addGridView(); // 添加一个gridView
			year_c = Integer.parseInt(currentDate.split("-")[0]);
			month_c = Integer.parseInt(currentDate.split("-")[1]);
			day_c = Integer.parseInt(currentDate.split("-")[2]);
			calV = new CalendarAdapter(this, getResources(), jumpMonth,
					jumpYear, year_c, month_c, day_c);
			gridView.setAdapter(calV);
			addTextToTopTextView(topText);
			gvFlag++;

			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		return this.gestureDetector.onTouchEvent(event);
	}

	@Override
	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	// 添加头部的年份 闰哪月等信息
	public void addTextToTopTextView(TextView view) {
		StringBuffer textDate = new StringBuffer();
		textDate.append(calV.getShowYear()).append("年")
				.append(calV.getShowMonth()).append("月").append("\t");
		view.setText(textDate);
		view.setTextColor(Color.WHITE);
		view.setTypeface(Typeface.DEFAULT_BOLD);
	}

	// 添加gridview
	private void addGridView() {

		gridView = (GridView) findViewById(R.id.gridview);

		gridView.setOnTouchListener(new OnTouchListener() {
			// 将gridview中的触摸事件回传给gestureDetector
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				return JianchiPage.this.gestureDetector.onTouchEvent(event);
			}
		});

		gridView.setOnItemClickListener(new OnItemClickListener() {
			// gridView中的每一个item的点击事件

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// 点击任何一个item，得到这个item的日期(排除点击的是周日到周六(点击不响应))
				int startPosition = calV.getStartPositon();
				int endPosition = calV.getEndPosition();
				if (startPosition <= position + 7
						&& position <= endPosition - 7) {
					String scheduleDay = calV.getDateByClickItem(position)
							.split("\\.")[0]; // 这一天的阳历
					// String scheduleLunarDay =
					// calV.getDateByClickItem(position).split("\\.")[1];
					// //这一天的阴历
					String scheduleYear = calV.getShowYear();
					String scheduleMonth = calV.getShowMonth();
					// Toast.makeText(CalendarActivity.this,
					// scheduleYear+"-"+scheduleMonth+"-"+scheduleDay,
					// 2000).show();
					ruzhuTime = scheduleMonth + "月" + scheduleDay + "日";
					lidianTime = scheduleMonth + "月" + scheduleDay + "日";
					Intent intent = new Intent();
					if (state.equals("ruzhu")) {

						bd.putString("ruzhu", ruzhuTime);
						System.out.println("ruzhuuuuuu" + bd.getString("ruzhu"));
					} else if (state.equals("lidian")) {

						bd.putString("lidian", lidianTime);
					}
					// intent.setClass(CalendarActivity.this,
					// HotelActivity.class);
					// intent.putExtras(bd);
					// startActivity(intent);
					// finish();
				}
			}

		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		SelectEveryDayTask();
	}

	public void SelectEveryDayTask() {
		cursor = EveryDaytaskReader.query(EveryDayTask.TABLE_NAME, null, null,
				null, null, null, null);
		adapter = new EveryDayTaskAdapter(this, cursor);
		everydaytasklist.setAdapter(adapter);
	}

}

class EveryDayTaskAdapter extends BaseAdapter {

	private Context context;
	private Cursor cursor;
	private LinearLayout layout;

	public EveryDayTaskAdapter(Context context, Cursor cursor) {
		this.context = context;
		this.cursor = cursor;
	}

	@Override
	public int getCount() {
		return cursor.getCount();
	}

	@Override
	public Object getItem(int position) {
		return cursor.getPosition();
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = LayoutInflater.from(context);
		layout = (LinearLayout) inflater.inflate(R.layout.everydaytaskcell,
				null);
		TextView contenttext = (TextView) layout
				.findViewById(R.id.everydaytask_content);
		cursor.moveToPosition(position);
		String content = cursor.getString(cursor.getColumnIndex("content"));
		contenttext.setText(content);
		return layout;
	}

}
